////////////////////////////////////////////////////////////////////////////////
// File:        DownloadLicensesFrm.cpp
// Purpose:     Implementation of the Licenses Downloader Frame
// Author:      Tukero
// Modified by: 
// Copyright:   (c) Tukero <tukero@gmail.com>
// Licence:     GNU/LGPL v3
////////////////////////////////////////////////////////////////////////////////

#include "CurrentAppHeaders.h"
#include "TNod.h"
#include "Multilanguage.h"
#include "DownloadLicensesFrm.h"
#include "PassServers.h"
#include "EsetManager.h"
#include <wx/file.h>

//----------------------------------------------------------------------------
// DownloadLicensesFrm
//----------------------------------------------------------------------------
//Add Custom Events only in the appropriate block.
//Code added in other places will be removed by wxDev-C++
////Event Table Start
BEGIN_EVENT_TABLE(DownloadLicensesFrm,wxFrame)
	////Manual Code Start
	////Manual Code End
	
	EVT_CLOSE(DownloadLicensesFrm::OnClose)
    EVT_BUTTON(ID_M_BTNDOWNLOAD,DownloadLicensesFrm::OnBtnDownload)
    EVT_BUTTON(ID_M_BTNCLOSE,DownloadLicensesFrm::OnBtnClose)
    EVT_MENU(ID_RECEIVEEVENTS, DownloadLicensesFrm::OnExternalEvent)
    EVT_MENU(ID_ITEM_INSERTLICENSE, DownloadLicensesFrm::OnInsertLicense)
    EVT_MENU(ID_ITEM_COPYUSERNAME, DownloadLicensesFrm::OnCopyUsername)
    EVT_MENU(ID_ITEM_COPYPASSWORD, DownloadLicensesFrm::OnCopyPassword)
    EVT_MENU(ID_ITEM_COPY2CLIPBOARD, DownloadLicensesFrm::OnCopy2Clipboard)
    EVT_BUTTON(ID_M_BTNSAVE2FILE, DownloadLicensesFrm::OnBtnSave2File)
    EVT_LIST_ITEM_RIGHT_CLICK(ID_M_LVWLICENSES,DownloadLicensesFrm::OnLvwRightClick)
END_EVENT_TABLE()
////Event Table End

DownloadLicensesFrm::DownloadLicensesFrm(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)
: wxFrame(parent, id, title, position, size, style)
{
    m_runningThread = NULL;
    m_insertionThread = NULL;
    m_RunsWithoutUpdate = 0;
	CreateGUIControls();    
}

DownloadLicensesFrm::~DownloadLicensesFrm()
{
}

void DownloadLicensesFrm::CreateGUIControls()
{
	//Do not add custom code between
	//GUI Items Creation Start and GUI Items Creation End
	//wxDev-C++ designer will remove them.
	//Add the custom code before or after the blocks
	////GUI Items Creation Start

	m_boxMain = new wxBoxSizer(wxHORIZONTAL);
	this->SetSizer(m_boxMain);
	this->SetAutoLayout(true);

	m_panMain = new wxPanel(this, ID_M_PANMAIN, wxPoint(0, 0), wxSize(401, 324));
	m_boxMain->Add(m_panMain,1,wxEXPAND | wxALL,0);

	m_sizerDrawing = new wxBoxSizer(wxVERTICAL);
	m_panMain->SetSizer(m_sizerDrawing);
	m_panMain->SetAutoLayout(true);

	wxStaticBox* m_bxsOptions_StaticBoxObj = new wxStaticBox(m_panMain, wxID_ANY, wxT(""));
	m_bxsOptions = new wxStaticBoxSizer(m_bxsOptions_StaticBoxObj, wxHORIZONTAL);
	m_sizerDrawing->Add(m_bxsOptions, 0, wxEXPAND | wxALL, 5);

	m_lvwLicenses = new wxListCtrl(m_panMain, ID_M_LVWLICENSES, wxPoint(5, 130), wxSize(384, 114), wxLC_REPORT | wxLC_SINGLE_SEL | wxLC_SORT_ASCENDING|wxLC_HRULES | wxLC_VRULES, wxDefaultValidator, wxT("m_lvwLicenses"));
	m_sizerDrawing->Add(m_lvwLicenses,1,wxEXPAND | wxALL,5);

	m_flxDownloadOptions = new wxFlexGridSizer(0, 2, 0, 0);
	m_bxsOptions->Add(m_flxDownloadOptions, 0, wxALIGN_CENTER | wxALL, 5);

	m_lblLicenses2Download = new wxStaticText(m_panMain, ID_M_LBLLICENSES2DOWNLOAD,GETLANG(81), wxPoint(33, 7), wxDefaultSize, 0, wxT("m_lblLicenses2Download"));//licenses to download
	m_flxDownloadOptions->Add(m_lblLicenses2Download,0,wxALIGN_LEFT | wxALL,5);

	m_spinLicenses2Download = new wxSpinCtrl(m_panMain, ID_M_SPINLICENSES2DOWNLOAD, wxT("5"), wxPoint(229, 5), wxSize(57, 24), wxSP_ARROW_KEYS, 0, 999, 0);
	m_flxDownloadOptions->Add(m_spinLicenses2Download,0,wxALIGN_RIGHT | wxALL,5);

	m_lblLicenses2Check = new wxStaticText(m_panMain, ID_M_LBLLICENSES2CHECK, GETLANG(82), wxPoint(14, 41), wxDefaultSize);
	m_flxDownloadOptions->Add(m_lblLicenses2Check,0,wxALIGN_LEFT | wxALL,5);

	m_spinLicenses2Check = new wxSpinCtrl(m_panMain, ID_M_SPINLICENSES2CHECK, wxT("15"), wxPoint(229, 39), wxSize(57, 24), wxSP_ARROW_KEYS, 0, 100, 0);
	m_flxDownloadOptions->Add(m_spinLicenses2Check,0,wxALIGN_RIGHT | wxALL,5);

	m_lblLicesesValidFor = new wxStaticText(m_panMain, ID_M_LBLLICESESVALIDFOR, GETLANG(92), wxPoint(52, 75), wxDefaultSize, 0, wxT("m_lblLicesesValidFor"));
	m_flxDownloadOptions->Add(m_lblLicesesValidFor,0,wxALIGN_LEFT | wxALL,5);

	wxArrayString arrayStringFor_cboProductType;
	arrayStringFor_cboProductType.Add(wxT("EAV"));
	arrayStringFor_cboProductType.Add(wxT("ESS"));
	arrayStringFor_cboProductType.Add(wxT("EAVBE"));
	arrayStringFor_cboProductType.Add(wxT("ESSBE"));
	m_cboProductType = new wxComboBox(m_panMain, ID_M_CBOPRODUCTTYPE, wxT("cboProductType"), wxPoint(229, 73), wxSize(57, 23), arrayStringFor_cboProductType, wxCB_DROPDOWN | wxCB_READONLY, wxDefaultValidator, wxT("cboProductType"));
	m_flxDownloadOptions->Add(m_cboProductType,0,wxALIGN_CENTER | wxALL,5);


	m_btnSave2File = new wxButton(m_panMain, ID_M_BTNSAVE2FILE, GETLANG(84), wxPoint(128, 251), wxSize(137, 25), 0, wxDefaultValidator, wxT("m_btnSave2File"));
	m_sizerDrawing->Add(m_btnSave2File,0,wxALIGN_CENTER | wxALL,2);

	m_linSeparator = new wxStaticLine(m_panMain, ID_M_LINSEPARATOR, wxPoint(2, 280), wxSize(390, -1), wxLI_HORIZONTAL);
	m_sizerDrawing->Add(m_linSeparator,0,wxALIGN_CENTER | wxALL,2);

	m_btnDownload = new wxButton(m_panMain, ID_M_BTNDOWNLOAD, GETLANG(85), wxPoint(299, 42), wxSize(75, 41), 0, wxDefaultValidator, wxT("m_btnDownload"));
	m_bxsOptions->Add(m_btnDownload,0,wxALIGN_CENTER | wxALL,5);

	m_chkCheckExpirationDates = new wxCheckBox(m_panMain, ID_M_CHKCHECKEXPIRATIONDATES, GETLANG(83), wxPoint(5, 73), wxSize(214, 17), 0, wxDefaultValidator, wxT("m_chkCheckExpirationDates"));
	m_flxDownloadOptions->Add(m_chkCheckExpirationDates,0,wxALIGN_LEFT | wxALL,5);

	m_btnClose = new wxButton(m_panMain, ID_M_BTNCLOSE, GETLANG(26), wxPoint(159, 294), wxSize(75, 25), 0, wxDefaultValidator, wxT("m_btnClose"));
	m_sizerDrawing->Add(m_btnClose,0,wxALIGN_RIGHT | wxALL,5);

	SetTitle( GETLANG(80) + wxT(" - TNod ") + wxGetApp().GetStrVersion(2) );
    SetIcon(wxICON(appicon));
	
	GetSizer()->Layout();
	GetSizer()->Fit(this);
	GetSizer()->SetSizeHints(this);
	Center();
	
	////GUI Items Creation End

    m_spinLicenses2Check->SetValue( wxConfig::Get()->Read(wxT("DownloadLicDlg/Lic2Check"),MAXPASS) );
    m_spinLicenses2Download->SetValue( wxConfig::Get()->Read(wxT("DownloadLicDlg/Lic2Download"),5L) );
    m_chkCheckExpirationDates->SetValue( wxConfig::Get()->Read(wxT("DownloadLicDlg/CheckExpiration"),0L) == 1L );
    m_cboProductType->SetSelection( wxConfig::Get()->Read(wxT("DownloadLicDlg/ProductType"),0L) );

    m_oldProductSelection = m_cboProductType->GetSelection();

    wxListItem itemCol;
    itemCol.SetText(GETLANG(86));// _T("Username")
    itemCol.SetImage(-1);
    itemCol.SetWidth(130);
    m_lvwLicenses->InsertColumn(0, itemCol);    

    itemCol.SetText(GETLANG(87));//_T("Password")
    itemCol.SetAlign(wxLIST_FORMAT_LEFT);
    itemCol.SetWidth(120);
    m_lvwLicenses->InsertColumn(1, itemCol);

    itemCol.SetText(GETLANG(88));//_T("Expiration")
    itemCol.SetAlign(wxLIST_FORMAT_RIGHT);
    itemCol.SetWidth(115);
    m_lvwLicenses->InsertColumn(2, itemCol);

    m_DownloadEvent = NULL;
    m_indexOfSelection = -1;
}

//
// Event when the frame is going to close
//
void DownloadLicensesFrm::OnClose(wxCloseEvent& WXUNUSED(event))
{
    if (m_runningThread)
        //m_runningThread->Delete();
        m_runningThread->Kill();
    if (m_insertionThread)
        m_insertionThread->Kill();

    wxConfig::Get()->Write( wxT("DownloadLicDlg/Lic2Check"),m_spinLicenses2Check->GetValue() );
    wxConfig::Get()->Write( wxT("DownloadLicDlg/Lic2Download"),m_spinLicenses2Download->GetValue() );
    wxConfig::Get()->Write( wxT("DownloadLicDlg/CheckExpiration"),m_chkCheckExpirationDates->GetValue() );
    wxConfig::Get()->Write( wxT("DownloadLicDlg/ProductType"),m_cboProductType->GetSelection() );

    Hide();
    wxTheApp->ProcessPendingEvents();
    wxGetApp().Finish();
}

//
// Close - button click
//
void DownloadLicensesFrm::OnBtnClose(wxCommandEvent& WXUNUSED(event))
{
    Close();
}

//
// Download Licenses - button click
//
void DownloadLicensesFrm::OnBtnDownload(wxCommandEvent& WXUNUSED(event))
{
    EsetManager *esetManager = new EsetManager();
    esetManager->LoadInfo();
    esetManager->SetVersionType(m_cboProductType->GetValue().Lower());    

    m_lvwLicenses->DeleteAllItems();
    UpdateFirstColText();
    m_runningThread = new TNod(esetManager);
    TNod *tnodThread = (TNod*)m_runningThread;
    m_DownloadEvent = new wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, ID_RECEIVEEVENTS);

    wxGetApp().m_validLicenses2Get = m_spinLicenses2Download->GetValue();
    wxGetApp().m_licensesNum2Check = m_spinLicenses2Check->GetValue();

    tnodThread->SetEventReceiver(this,m_DownloadEvent, TNod::EVENT_GOTLICENSE);
    //tnod->SetEventReceiver(this,m_DownloadEvent, TNod::EVENT_GOTLICENSE);

       
    tnodThread->m_Actions2Do = TNod::GET_LICENSE;

    if (m_oldProductSelection != m_cboProductType->GetSelection())
        m_RunsWithoutUpdate = 0;
    if ( m_RunsWithoutUpdate == 0 )
    {
        tnodThread->m_Actions2Do |= TNod::CHECK_UPDATES;
        tnodThread->SetProcessNewVersionMsg(true, true);
    }

    m_RunsWithoutUpdate++;
    if ( m_RunsWithoutUpdate >= 4 )
        m_RunsWithoutUpdate = 0;
   

    tnodThread->SetEndIndicator((void **)&m_runningThread);
    m_checkExpirationDates = m_chkCheckExpirationDates->GetValue();
    if ( m_checkExpirationDates == true )
        tnodThread->m_Actions2Do |= TNod::CHECK_EXPIRATION;
    //tnod->m_CheckExpirationDate = m_chkCheckExpirationDates->GetValue();
    if ( tnodThread->Create() != wxTHREAD_NO_ERROR )
    {
        wxLogError(wxT("Can't create tnod thread!"));
        return;
    }
    m_runningThread->Run();	
    m_oldProductSelection = m_cboProductType->GetSelection();
}

//
// Receives the licenses events (when a valid license if found or when the licenses checking process is over)
//
void DownloadLicensesFrm::OnExternalEvent(wxCommandEvent& event)
{
    if (event.GetInt() == 1)
    {        
        if ( m_checkExpirationDates == false )
        {
            License *license = (License *)event.GetClientData();
            InsertLic2ListView(license);
        }
        
    }
    else if (event.GetInt() == 2)
    {
        wxDELETE(m_DownloadEvent)
    }
    else if (event.GetInt() == 3)
    {
        License *license = (License *)event.GetClientData();

        InsertLic2ListView(license);
    }
}

void DownloadLicensesFrm::InsertLic2ListView(License* license)
{
    if ((unsigned int)m_lvwLicenses->GetItemCount() >= wxGetApp().m_validLicenses2Get )
        return;

    if (license != NULL)
    {
        long id = m_lvwLicenses->InsertItem(m_lvwLicenses->GetItemCount(),license->GetUsername());
        m_lvwLicenses->SetItem(id,1,license->GetPassword());
        if ( license->GetExpirationDate() > 0 && m_checkExpirationDates == true )
        {
            wxDateTime date((time_t)license->GetExpirationDate());
            m_lvwLicenses->SetItem(id,2,date.Format(wxT("%d/%m/%Y")));
        }
        UpdateFirstColText();
    }
}

void DownloadLicensesFrm::UpdateFirstColText()
{
    if (m_lvwLicenses != NULL && m_lvwLicenses->GetColumnCount() > 0)
    {
        wxListItem firstCol;
        m_lvwLicenses->GetColumn(0,firstCol);
        wxString firstColText;

        int totalItems = m_lvwLicenses->GetItemCount();
        if (totalItems > 0)
            firstColText.Printf(wxT("%s (%d)"), GETLANG(86), totalItems);
        else
            firstColText = GETLANG(86);
        
        firstCol.SetText( firstColText );
        
        m_lvwLicenses->SetColumn(0, firstCol);
        
        
    }
}

//
// Save to a File - button click
//
void DownloadLicensesFrm::OnBtnSave2File(wxCommandEvent& WXUNUSED(event))
{
    if (m_lvwLicenses->GetItemCount() == 0)
    {
        wxMessageBox(GETLANG(89),wxT("TNod"),4|wxCENTRE|wxICON_EXCLAMATION);//no licenses no save. message
        return;
    }
    wxFileDialog dialog(this,
                        GETLANG(84),
                        wxEmptyString,
                        _T("DownloadedLicenses.txt"),
                        _T("Text files (*.txt)|*.txt|All Files (*.*)|*.*"),
                        wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

    dialog.SetFilterIndex(0);

    if (dialog.ShowModal() == wxID_OK)
    {        
        wxString contentOfFile;

        wxFile file4License(dialog.GetPath(),wxFile::write);
        if ( file4License.IsOpened() )
        {
            int c=0;
            wxString username, password, expiration;
            for (c=0; c< m_lvwLicenses->GetItemCount(); c++)
            {
                GetItemData(c,username, password, expiration);

                contentOfFile = wxT("Username: ") + username + wxT("\r\nPassword: ") + password;
                if (!expiration.IsEmpty())
                    contentOfFile += wxT("\r\nExpiration: ") + expiration;

                contentOfFile += wxT("\r\n\r\n");
                
                file4License.Write(contentOfFile);
            }
            file4License.Close();
        }
    }
}

//
// Licenses list - right click
//
void DownloadLicensesFrm::OnLvwRightClick(wxListEvent& event)
{
    m_indexOfSelection = event.GetIndex();

    wxMenu menu;

    menu.Append(ID_ITEM_INSERTLICENSE, GETLANG(90));
    menu.AppendSeparator();
    menu.Append(ID_ITEM_COPYUSERNAME, GETLANG(93));
    menu.Append(ID_ITEM_COPYPASSWORD, GETLANG(94));
    menu.Append(ID_ITEM_COPY2CLIPBOARD, GETLANG(91));

    PopupMenu(&menu);
}

//
// Insert License - menu click
//
void DownloadLicensesFrm::OnInsertLicense(wxCommandEvent& WXUNUSED(event))
{
    if (m_indexOfSelection >= 0)
    {
        wxString username, password, expiration;
        GetItemData(m_indexOfSelection, username, password, expiration);
       
        m_insertionThread = new TNod();
        TNod *tnodThread = (TNod *)m_insertionThread;

        tnodThread->SetEndIndicator((void **)&m_insertionThread);
        if ( tnodThread->Create() != wxTHREAD_NO_ERROR )
        {
            wxLogError(wxT("Can't create tnod thread!"));
            return;
        }
        tnodThread->m_License2Insert = new License(username, password);
        tnodThread->m_Actions2Do = TNod::INSERT_LICENSE;        
        tnodThread->Run();	

    }
}

//
// Copy username - menu click
//
void DownloadLicensesFrm::OnCopyUsername(wxCommandEvent& WXUNUSED(event))
{
    if (m_indexOfSelection >= 0)
    {
        wxString username, password, expiration;
        GetItemData(m_indexOfSelection, username, password, expiration);

        Utils::Copy2Clipboard(username);
    }
}

//
// Copy password - menu click
//
void DownloadLicensesFrm::OnCopyPassword(wxCommandEvent& WXUNUSED(event))
{
    if (m_indexOfSelection >= 0)
    {
        wxString username, password, expiration;
        GetItemData(m_indexOfSelection, username, password, expiration);

        Utils::Copy2Clipboard(password);
    }
}


//
// Copy to Clipboard - menu click
//
void DownloadLicensesFrm::OnCopy2Clipboard(wxCommandEvent& WXUNUSED(event))
{
    if (m_indexOfSelection >= 0)
    {
        wxString username, password, expiration;
        GetItemData(m_indexOfSelection, username, password, expiration);

        wxString text2Copy = wxT("Username: ") + username + wxT("\r\nPassword: ") + password;
        if (!expiration.IsEmpty())
            text2Copy += wxT("\r\nExpiration: ") + expiration;

        Utils::Copy2Clipboard(text2Copy);
    }
}

//
// Gets the item data of the item with determinated username and password
//
void DownloadLicensesFrm::GetItemData(int index, wxString& username, wxString& password, wxString& expiration)
{
    if (index >= 0)
    {
        username = m_lvwLicenses->GetItemText(index);

        wxListItem itemInfo;
        itemInfo.SetId(index);
        itemInfo.SetColumn(1);
        itemInfo.SetMask(wxLIST_MASK_TEXT);
        m_lvwLicenses->GetItem(itemInfo);

        password = itemInfo.GetText();

        itemInfo.SetColumn(2);
        m_lvwLicenses->GetItem(itemInfo);

        expiration = itemInfo.GetText();
    }
}